package com.jwmp.rbac.util;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.*;
import java.util.function.Consumer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Stream;

/**
 * ClassName 获取
 * @version 1.0
 */

public class ClassUtils {
	private static final String CLASS_SUFFIX = ".class";
	private static final String CLASS_FILE_PREFIX = File.separator + "classes"  + File.separator;

	private static List<String> result =  new ArrayList<>();
	/**
	 * 查找包下的所有类的名字
	 * @param packageName
	 * @return List集合，内容为类的全名
	 */
	public static List<String> getClazzNameByPackageName(String packageName) {
		File file = package2File(packageName);
		getAllClassName(file);
		return result;
	}

	/**
	 * 将传入的包名转化为 File 对象
	 * @param packageName 包名
	 * @return	包的 File 对象
	 */
	private static File package2File(String packageName){
		// 将包名改为路径
		String suffixPath = packageName.replaceAll("\\.", "/");

		// 获取包的绝对路径，转为路径好遍历内部文件
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		URL url = loader.getResource(suffixPath);

		return url != null ? new File(url.getPath()) : null;
	}
	
	/**
	 * 递归获取所有class文件的名字
	 * @param file  类 File 对象
	 * @return List 类名集合
	 */
	private static void getAllClassName(File file) {
		if(file.isDirectory()){
			File[] files = file.listFiles();
			for (File f : files) {
				if (f.isDirectory()) {
					getAllClassName(f);
				}else{
					String path = f.getPath();
					if(path.endsWith(CLASS_SUFFIX)) {
						path = path.replace(CLASS_SUFFIX, "");
						// 从 /classes/ 后面开始截取
						String clazzName = path.substring(path.indexOf(CLASS_FILE_PREFIX) + CLASS_FILE_PREFIX.length())
								.replace(File.separator, ".");
						result.add(clazzName);
					}
				}
			}
		}
	}
	
	public static void main(String[] args) {
		// System.out.println(getClazzNameByPackageName("com.jwmp.base.web.servlet"));
		List<Integer> list = Arrays.asList(5, 2, 3,6,9);
		System.out.println(list.parallelStream().findAny().get());
		System.out.println(list.stream().findAny().get());
	}
}
